package jdbchomework;

import java.sql.*;
import java.util.*;

public class SqlCon {
	static Scanner sca = new Scanner(System.in);

	static String com = "", sql = "";
	static int a;

	public static void main(String args[]) throws Exception {
		System.out.println("清输入你要选择的数据库：");

		String cho = sca.next();

		if ("Oracle".equals(cho)) {
			SqlCon sc = new SqlCon();
			sc.opr();
		} else if ("MySql".equals(cho)) {
			SqlCon sc = new SqlCon();
		} else {
			System.out.println("你输入的命令不正确");
		}
	}

	public void opr() throws Exception {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		System.out.println("SQL>");
		try {
			// // 1.加载驱动 －－－－－写法固定
			// Class.forName(driverName);
			// 2.连数据库－－－－－写法固定
			// getConn是伪代码
			con = JdbcUtil.getConn();
			// 3.获取数据库操作对象(SQL)
			int i = 2;
			// 4.操作数据库
			while (true) {
				com = sca.nextLine();
				sql = sql + " " + com;
				if (sql.endsWith(";")) {
					sql = sql.substring(0, sql.length() - 1);
					break;
				}
				System.out.print(i + " >");
				i++;
			}

			// ps = con.prepareStatement(sql);
			// for(int b =20081111;b<200081028;b++){
			// ps.setInt(1, b);
			// ps.setString(2, "MicroSoft"+b);
			// }
			// a = ps.executeUpdate();
			// System.out.println("更新了 "+a);

			rs = ps.executeQuery(sql);
			// 如果结果己是false，即使更新，
			// 如果结果集是true，即使查询
			boolean f = ps.execute(sql);
			if (f) {
				StringBuffer sb = new StringBuffer();
				rs = ps.getResultSet();
				while (rs.next()) {
					sb.append("id = " + rs.getInt(1) + " ");
					sb.append("name = " + rs.getString(2) + "\t");
					sb.append("sex = " + rs.getString(3) + "\t");
					sb.append("birthday = " + rs.getString(4) + "\t");
					sb.append("political= " + rs.getString(5) + "\n");
				}
				System.out.println(sb.toString());
			} else {
				int b = ps.getUpdateCount();
				System.out.println("更新了" + b + "条记录");
			}

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("操作失败");
		} finally {
			JdbcUtil.close(rs, ps, con);
		}
	}

}
